import Vue from 'vue'
import Vuex from 'vuex'


Vue.use(Vuex)

export default new Vuex.Store({
  // state 在 Vuex 中用于存储数据
  state: {
    isLogin: null, // 用户登录状态
    name: null, // 用户登录信息
    expires: null,// 
    token: null, //登录 token 值
    key: true,
    collection: [],
    like: [],
    route: '' // 跳转前路由
  },
  // mutations 里面存放方法，主要用于改变 state 里面的数据
  mutations: {
    /**
     * 保存登录信息
     */
    setLoginInfo(state, data) {
      state.name = data.name;
      state.expires = data.expires;
      state.isLogin = true;
      state.token = data.token;
      localStorage.setItem('name', state.name);
      localStorage.setItem('expires',state.expires);
      localStorage.setItem('token',state.token);
      localStorage.setItem('isLogin',true);
    },
    /**
     * 清除登录信息
     */
    setLogoutInfo(state) {
      state.name = null;
      state.expires = null;
      state.token = null;
      state.isLogin = false;
      state.collection = [],
      state.like = [],
      localStorage.setItem('isLogin',false);
      localStorage.setItem('name', '');
      localStorage.setItem('token', '');
      localStorage.setItem('expires', '');
    },
    /**
     * 读取本地登录信息
     */
    getLocalStorage(state) {
      if(localStorage.getItem('isLogin')==='true'){
        state.isLogin = true;
      } else {
        state.isLogin = false;
      }
      state.name = localStorage.getItem('name');
      state.expires = localStorage.getItem('expires');
      state.token = localStorage.getItem('token');
    },
    /**
     * 保存收藏列表
     */
    setUserInfo(state, data) {
      state.collection = data.collect;
      state.like = data.like;
    },
    resetKey(state) {
      state.key = state.key ? false : true;
    },
    changeLike(state, id) {
      var index = state.like.indexOf(id);
      if (index != -1) {
        state.like.splice(index, 1);
      } else {
        state.like.push(id);
      }
    },
    changeCollection(state, id) {
      var index = state.collection.indexOf(id);
      if (index != -1) {
        state.collection.splice(index, 1);
      } else {
        state.collection.push(id);
      }
    },
    setRoute(state, path) {
      state.route = path;
    },
    clearRoute(state){
      state.route = '';
    }
  },
  // actions 类似于 mutations ,不过不是直接变更状态，而提交的是 mutation ，可以包含任意异步操作
  actions: {

  }
})